﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Security;

namespace WebApplicationApi.Utilities.Filter
{
  public class CustomAuthorizeAttribute : AuthorizeAttribute
  {
    public override void OnAuthorization(HttpActionContext actionContext)
    {
      var authorization = actionContext.Request.Headers.Authorization;
      if (authorization == null)
      {
        this.HandlerUnAuthorization();
      }
      else if (ValidateTicket(authorization.Parameter))
      {
        return;
      }
      else
      {
        this.HandlerUnAuthorization();
      }
    }
    private void HandlerUnAuthorization()
    {
      throw new HttpResponseException(System.Net.HttpStatusCode.Unauthorized);


    }
    private bool ValidateTicket(string encryptTicket)
    {
      try
      {
        //此处应该取数据库校验
        var strTicket = FormsAuthentication.Decrypt(encryptTicket).UserData;
        if (string.Equals(strTicket, $"userName:{"admin"},password:{"123456"}"))
          return true;
        else
          return false;
      }
      catch (Exception)
      {
        return false;
      }
    }
  }
}